# _*_ coding : utf-8 _*_
# @Time : 2025/3/29 11:08
# @Author : 梁满仓
# @File : stock_history_data
# @Project : stock_of_donnie_day_day_up
import akshare as ak

#save_path = 'stock_data/Unadjusted/'
save_path = 'stock_data/Forward_Adjusted/'
#save_path = 'stock_data/Backward_Adjusted/'


# 获取 A 股所有上市公司的代码和名称
stock_info_a_code_name_df = ak.stock_info_a_code_name()

# 指定日期范围，格式为 'YYYYMMDD'
start_date = "20000101"
end_date = "20250101"

# 循环获取每一家公司的股票数据并保存
for index, row in stock_info_a_code_name_df.iterrows():
    stock_code = row['code']
    stock_name = row['name']
    # 组合文件名，例如：贵州茅台 600519.SH.csv
    #file_name = f"{stock_code}_{stock_name}.csv"
    file_name = f"{stock_code}.csv"

    try:
        stock_individual_info_em_df = ak.stock_individual_info_em(symbol=stock_code)
        # 通过布尔索引筛选出上市时间
        start_date = stock_individual_info_em_df[stock_individual_info_em_df['item'] == '上市时间']['value'].values[0]
        #print(start_date)
        # 获取股票日线行情数据，可根据实际需求换用其他合适的数据接口
        #后复权
        #stock_data = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=start_date, end_date=end_date, adjust="hfq")
        #不复权
        #stock_data = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=start_date, end_date=end_date)
        #前复权
        stock_data = ak.stock_zh_a_hist(symbol=stock_code, period="daily", start_date=start_date, end_date=end_date, adjust="qfq")
        # 将数据保存为 CSV 文件
        stock_data.to_csv(save_path + file_name, index=False)
        print(f"{index}-{stock_name}（{stock_code}）的数据已成功保存到 {file_name}")
    except Exception as e:
        print(f"获取 {index}-{stock_name}（{stock_code}）的数据时出现错误：{str(e)}")


